<template>
  <el-input
    v-if="column.search?.el === 'input'"
    v-bind="{ ...handleSearchProps, ...placeholder, searchParam: _searchParam, clearable }"
    v-model.trim="_searchParam[column.search?.key ?? util.handleProp(column.prop!)]" />
  <el-select
    v-if="column.search?.el === 'select'"
    v-bind="{ ...handleSearchProps, ...placeholder, searchParam: _searchParam, clearable }"
    v-model.trim="_searchParam[column.search?.key ?? util.handleProp(column.prop!)]">
    <el-option
      v-for="(col, index) in columnEnum"
      :key="index"
      :label="col[fieldNames.label]"
      :value="col[fieldNames.value]" />
  </el-select>
  <slot v-else></slot>
</template>

<script setup lang="ts" name="SearchFormItem">
import { computed, inject, ref } from 'vue';
import { util } from '@/utils';
import type { ColumnProps } from '@/components/proTable/interface';

interface SearchFormItem {
  column: ColumnProps;
  searchParam: { [key: string]: any };
}
const props = defineProps<SearchFormItem>();

// Re receive SearchParam
const _searchParam = computed(() => props.searchParam);

// 判断 fieldNames 设置 label && value && children 的 key 值
const fieldNames = computed(() => {
  return {
    label: props.column.fieldNames?.label ?? 'label',
    value: props.column.fieldNames?.value ?? 'value',
  };
});

// 接收 enumMap
const enumMap = inject('enumMap', ref(new Map()));
const columnEnum = computed(() => {
  let enumData = enumMap.value.get(props.column.prop);
  if (!enumData) return [];
  return enumData;
});

// 处理透传的 searchProps
const handleSearchProps = computed(() => {
  return props.column.search?.props ?? {};
});

// 处理默认 placeholder
const placeholder = computed(() => {
  const search = props.column.search;
  if (['datetimerange', 'daterange', 'monthrange'].includes(search?.props?.type) || search?.props?.isRange) {
    return {
      rangeSeparator: search?.props?.rangeSeparator ?? '至',
      startPlaceholder: search?.props?.startPlaceholder ?? '开始时间',
      endPlaceholder: search?.props?.endPlaceholder ?? '结束时间',
    };
  }
  const placeholder = search?.props?.placeholder ?? (search?.el?.includes('input') ? '请输入' : '请选择');
  return { placeholder };
});

// 是否有清除按钮 (当搜索项有默认值时，清除按钮不显示)
const clearable = computed(() => {
  const search = props.column.search;
  return search?.props?.clearable ?? (search?.defaultValue == null || search?.defaultValue == undefined);
});
</script>
